package com.eqdd.yiqidian.ui.tongxunlu;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import com.arlib.floatingsearchview.FloatingSearchView;
import com.arlib.floatingsearchview.suggestions.model.SearchSuggestion;
import com.eqdd.floatingmenu.MenuItem;
import com.eqdd.floatingmenu.TopRightMenu;
import com.eqdd.library.percentUtil.WindowUtil;
import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.StaffActivityCustom;
import com.eqdd.yiqidian.adapter.recycleadapter.ItemClickSupport;
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx;
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector;
import com.eqdd.yiqidian.adapter.slimadapter.viewinjector.IViewInjector;
import com.eqdd.yiqidian.base.BaseActivity;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.rebuild.EmploymentListResultBean;
import com.eqdd.yiqidian.bean.rebuild.ListResultBean;
import com.eqdd.yiqidian.helper.mvchelper.ModelRx2DataSource;
import com.eqdd.yiqidian.http.DialogCallBack;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.HttpResult;
import com.eqdd.yiqidian.http.JsonConverter;
import com.eqdd.yiqidian.ui.mine.UserCardActivity;
import com.eqdd.yiqidian.utils.IMUtil;
import com.eqdd.yiqidian.utils.ImageUtil;
import com.eqdd.yiqidian.utils.IntentUtil;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.lzy.okrx2.adapter.FlowableBody;
import com.shizhefei.mvc.MVCCoolHelper;

import org.reactivestreams.Publisher;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Flowable;
import io.reactivex.functions.Function;

/**
 * Created by 吕志豪 on 17-10-14  下午4:35.
 * Github :https://github.com/lvzhihao100
 * E-Mail：1030753080@qq.com
 * 简书 :http://www.jianshu.com/u/6e525b929aac
 */

public class StaffActivity extends BaseActivity {

    private StaffActivityCustom dataBinding;
    private SlimAdapterEx<EmploymentListResultBean> slimAdapterEx;
    private MVCCoolHelper<List<EmploymentListResultBean>> mvcHelper;
    private int pageIndex = 0;
    private TopRightMenu mTopRightMenu;

    @Override
    public void initBinding() {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_staff);
        initTopTitleBar(View.VISIBLE, "同事");
    }

    @Override
    public void initData() {

        dataBinding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        slimAdapterEx = SlimAdapterEx.create()
                .register(R.layout.list_item_10, new SlimInjector<EmploymentListResultBean>() {
                    @Override
                    public void onInject(EmploymentListResultBean data, IViewInjector injector) {
                        injector.text(R.id.tv_upper_left_content, data.getStaffName())
                                .text(R.id.tv_upper_right_content, data.getDepartName())
                                .text(R.id.tv_down_right_content, data.getPostName())
                                .with(R.id.iv_head, v -> {
                                    ImageUtil.setCircleImage(data.getIphoto(), (ImageView) v);
                                })
                                .invisible(R.id.iv_enter);
                    }
                })
                .attachTo(dataBinding.recyclerView).updateData(new ArrayList());
        ItemClickSupport.addTo(dataBinding.recyclerView)
                .setOnItemClickListener((recyclerView, position, v) -> {
                    EmploymentListResultBean emBean = (EmploymentListResultBean) slimAdapterEx.getData().get(position);
                    Bundle bundle = new Bundle();
                    bundle.putString(Config.GUID, emBean.getGuid());
                    startActivity(UserCardActivity.class, bundle);
                })
                .setOnItemLongClickListener((rv, p, v) -> {
                    if (slimAdapterEx.getData().get(p) instanceof EmploymentListResultBean) {
                        if (mTopRightMenu == null) {
                            mTopRightMenu = new TopRightMenu(StaffActivity.this);
                            List<MenuItem> menuItems = new ArrayList<>();
                            menuItems.add(new MenuItem("发送消息"));
                            menuItems.add(new MenuItem("拨打电话"));
//                            menuItems.add(new MenuItem("设置标签"));
                            mTopRightMenu
                                    .setHeight(WindowUtil.csw * 110 / WindowUtil.width)     //默认高度480
                                    .setWidth(WindowUtil.csw * 150 / WindowUtil.width)      //默认宽度wrap_content
                                    .showIcon(false)     //显示菜单图标，默认为true
                                    .dimBackground(true)        //背景变暗，默认为true
                                    .needAnimationStyle(true)   //显示动画，默认为true
                                    .setAnimationStyle(R.style.TRM_ANIM_STYLE)
                                    .addMenuList(menuItems)
                                    .setOnMenuItemClickListener((position) -> {
                                        System.out.println();
                                        switch (position) {
                                            case 0:
                                                IMUtil.startPrivate(StaffActivity.this, slimAdapterEx.getDataItem(p).getGuid(), slimAdapterEx.getDataItem(p).getStaffName(), slimAdapterEx.getDataItem(p).getIphoto());
                                                break;
                                            case 1:
                                                IntentUtil.call(StaffActivity.this, slimAdapterEx.getDataItem(position).getUname());
                                                break;
                                        }
                                    });
                        }
                        mTopRightMenu.showAsDropDown(v, 200, -80);    //带偏移量
                    }
                    return false;
                });
        dataBinding.floatingSearchView.setOnSearchListener(new FloatingSearchView.OnSearchListener() {
            @Override
            public void onSuggestionClicked(SearchSuggestion searchSuggestion) {
            }

            @Override
            public void onSearchAction(String currentQuery) {
                if (!TextUtils.isEmpty(currentQuery)) {
                    searchRequest(currentQuery);
                }
            }
        });
        mvcHelper = new MVCCoolHelper<>(dataBinding.coolRefreshView);
        ModelRx2DataSource<EmploymentListResultBean> dataSource = new ModelRx2DataSource<>((page, register) -> {
            return OkGo.<HttpResult<ListResultBean<EmploymentListResultBean>>>post(HttpConfig.BASE_URL + HttpConfig.SELECT_EMPLOYMENT_ALL)
                    .params("companyId", user.getCompanyId())
                    .params("page", page == 1 ? 0 : pageIndex)
                    .converter(new JsonConverter<HttpResult<ListResultBean<EmploymentListResultBean>>>() {
                        @Override
                        public void test() {
                            super.test();
                        }
                    })
                    .adapt(new FlowableBody<HttpResult<ListResultBean<EmploymentListResultBean>>>())
                    .flatMap(new Function<HttpResult<ListResultBean<EmploymentListResultBean>>, Publisher<List<EmploymentListResultBean>>>() {
                        @Override
                        public Publisher<List<EmploymentListResultBean>> apply(HttpResult<ListResultBean<EmploymentListResultBean>> listResultBeanHttpResult) throws Exception {
                            pageIndex = listResultBeanHttpResult.getItems().getPage();

                            return Flowable.just(listResultBeanHttpResult.getItems().getList());
                        }
                    });

        });
        mvcHelper.setDataSource(dataSource);
        mvcHelper.setAdapter(slimAdapterEx);
        mvcHelper.refresh();
    }

    private void searchRequest(String currentQuery) {
        OkGo.<HttpResult<List<EmploymentListResultBean>>>post(HttpConfig.BASE_URL + HttpConfig.SEARCH_EMPLOY)
                .params("para", currentQuery)
                .params("companyId", user.getCompanyId())
                .execute(new DialogCallBack<HttpResult<List<EmploymentListResultBean>>>(StaffActivity.this) {
                    @Override
                    public void onSuccess(Response<HttpResult<List<EmploymentListResultBean>>> response) {
                        HttpResult<List<EmploymentListResultBean>> httpResult = response.body();
                        ToastUtil.showShort(httpResult.getMsg());
                        if (httpResult.getStatus() == 200) {
                            slimAdapterEx.updateData(httpResult.getItems());
                        }
                    }
                });
    }

    @Override
    public void setView() {

    }
}
